package com.ruoyi.web.cp.schuedule;

import com.ruoyi.web.cp.service.AqService;
import com.ruoyi.web.cp.service.FbService;
import com.ruoyi.web.cp.service.SendFitService;
import com.ruoyi.web.cp.service.merge.MergeAqfbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Slf4j
@Configuration
public class AqfbTask {
    @Autowired
    private FbService fbService;
    @Autowired
    private AqService aqService;
    @Autowired
    private MergeAqfbService mergeService;
    @Autowired
    private Executor biggerTaskExecutor;
    @Autowired
    private SendFitService sendFitService;
    public static Integer FLAG2 = 1;

    @Scheduled(fixedDelayString = "300000")
    public void execute() {
        try {
            FLAG2 = 2;
            // 1. 更新 AQ 和 FB 详情
            CompletableFuture<Void> rmFuture = runAsyncTask(() -> aqService.getDetail(), "Error in updating AQ detail");
            CompletableFuture<Void> obFuture = runAsyncTask(() -> fbService.getFbDetail(), "Error in updating FB detail");
            //2. 合并 AQ 和 FB
            CompletableFuture.allOf(rmFuture, obFuture)
                    .thenRun(this::mergeAqOb)
                    .thenRun(sendFitService::sendAqfbFit)
                    .exceptionally(ex -> {
                        log.error("Error in executing all tasks", ex);
                        return null;
                    }).join();
        } finally {
            FLAG2 = 1;
        }
    }

    /**
     * 异步执行任务并捕获异常
     *
     * @param task   要执行的任务
     * @param errMsg 错误信息
     * @return CompletableFuture
     */
    private CompletableFuture<Void> runAsyncTask(Runnable task, String errMsg) {
        return CompletableFuture.runAsync(task, biggerTaskExecutor)
                .exceptionally(ex -> {
                    log.error(errMsg, ex);
                    return null;
                });
    }

    private void mergeAqOb() {
        runAsyncTask(() -> {
            log.info("开始执行-->mergeAqOb");
            mergeService.mergeAqfb();
        }, "Error in merging AQ and OB").join();
    }
}
